<template>
  <div class="page-container service">
    <van-nav-bar
      title="填写服务订单"
      left-text="返回"
      left-arrow
      fixed
      placeholder
      @click-left="onClickLeft"
    />

    <!-- 进度条区域 -->
    <div class="progress-bar">
      <van-steps :active="currentStep" active-color="#07c160">
        <van-step>填写订单</van-step>
        <van-step>待支付</van-step>
        <van-step>待服务</van-step>
        <van-step>已完成</van-step>
      </van-steps>
    </div>

    <!-- 服务类型展示 -->
    <div class="service-type">
      <div class="service-icon">
        <img :src="serviceImg" :alt="serviceType">
      </div>
      <div class="service-info">
        <div class="service-name" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '30px' : ''}">{{ serviceType }}</div>
        <div class="service-desc" :style="{fontSize:userStore.userInfo.ageGroup === 1 ? '15px' : ''}">{{ serviceDescription }}</div>
      </div>
    </div>

    <van-form @submit="onSubmit">
      <!-- 医院信息 -->
      <div class="form-block">
        <div class="block-title">医院信息</div>
        <van-cell-group inset>
          <van-field
            v-model="formData.hospitalName"
            label="医院名称"
            placeholder="请选择医院"
            readonly
            is-link
            :class="{'custom-label':userStore.userInfo.ageGroup === 1}"
            @click="isDisabled? showHospitalPicker = true : showHospitalPicker = false"
            :rules="[{ required: true, message: '请选择医院' }]"
          />
          <van-field
            v-if="serviceType ==='诊前约号'"
            v-model="departmentName"
            label="就诊科室"
            placeholder="请输入就诊科室"
            :rules="[{ required: true, message: '请输入就诊科室' },
            {
              pattern: /^.{1,10}$/, // 正则表达式校验科室名称格式
              message: '就诊科室名称长度不能超过10个字符',
            }
          ]"
            :class="{'custom-label':userStore.userInfo.ageGroup === 1}"
          />
          <van-field
            v-if="serviceType ==='诊前约号'"
            v-model="doctorName"
            label="就诊医生名字"
            placeholder="请输入就诊医生名字"
            :rules="[{ required: true, message: '请输入就诊医生名字' },
            {
              pattern: /^.{1,10}$/, // 正则表达式校验科室名称格式
              message: '就诊医生名字长度不能超过10个字符',
            }
          ]"
            :class="{'custom-label':userStore.userInfo.ageGroup === 1}"
          />
        </van-cell-group>
      </div>

      <!-- 服务对象信息 -->
      <div class="form-block">
        <div class="block-title">服务对象信息</div>
        <van-cell-group inset>
          <van-field
            v-model="formData.serviceObject"
            label="服务对象"
            placeholder="请选择服务对象"
            readonly
            is-link
            @click="showPatientPicker = true"
            :class="{'custom-label':userStore.userInfo.ageGroup === 1}"
          />
          <van-field
            v-model="formData.serviceObjectPhone"
            type="tel"
            label="服务对象电话"
            placeholder="请输入联系电话"
            :rules="[{ required: true, message: '请输入联系电话' },
            {
            pattern: /^1[3-9]\d{9}$/, // 正则表达式校验手机号格式
            message: '请输入正确的手机号',
            }
          ]"
            :class="{'custom-label':userStore.userInfo.ageGroup === 1}"
          />
          <van-field
            v-if="serviceType ==='代跑取药'"
            v-model="result"
            label="诊断结果"
            placeholder="请输入诊断结果"
            :rules="[{ required: true, message: '请输入诊断结果' },
            {
              pattern: /^.{1,50}$/, // 正则表达式校验科室名称格式
              message: '诊断结果长度不能超过50个字符',
            }
          ]"
            :class="{'custom-label':userStore.userInfo.ageGroup === 1}"
          />
          <van-field
            v-if="serviceType ==='代跑取药'"
            v-model="deliveryCode"
            label="取药码"
            placeholder="请输入取药码"
            :rules="[{ required: true, message: '请输入取药码' },
              {
                pattern: /^\d{1,10}$/, // 正则表达式校验取药码格式
                message: '取药码必须为1-10位纯数字',
              },
          ]"
            :class="{'custom-label':userStore.userInfo.ageGroup === 1}"
          />
          <van-field
            v-if="serviceType ==='送取就医结果' || serviceType ==='代跑取药'"
            v-model="idNumber"
            label="身份证号"
            placeholder="请输入身份证号"
            :rules="[{ required: true, message: '请输入身份证号' },
            {
              pattern: /^\d{17}[\dXx]$/, // 正则表达式校验身份证号格式
              message: '请输入有效的18位身份证号',
            },
          ]"
            :class="{'custom-label':userStore.userInfo.ageGroup === 1}"
          />
          <van-field
            v-if="serviceType ==='代跑取药'"
            v-model="medicalNumber"
            label="医保卡号"
            placeholder="请输入医保卡号"
            :rules = "[
                {
                  pattern: /^\d{10,20}$/, // 正则表达式校验医保卡号格式
                  message: '医保卡号必须为10-20位纯数字',
                },
            ]"
            :class="{'custom-label':userStore.userInfo.ageGroup === 1}"
          />
          <van-field
            v-if="serviceType ==='送取就医结果'"
            v-model="medicalCardNumber"
            label="就诊卡号"
            placeholder="请输入就诊卡号"
            :rules="[{ required: true, message: '请输入就诊卡号' },
            {
              pattern: /^\d{10,20}$/, // 正则表达式校验医保卡号格式
              message: '就诊卡号必须为10-20位纯数字',
            },
          ]"
            :class="{'custom-label':userStore.userInfo.ageGroup === 1}"
          />
          <van-field
            v-if="serviceType ==='就医陪诊' || serviceType ==='送取就医结果' || serviceType ==='代跑取药' || serviceType ==='上门陪护'"
            v-model="address"
            type="tel"
            :label="serviceType ==='就医陪诊' ? '接送地址' : serviceType ==='上门陪护' ? '陪护地址' : '接收地址'"
            :placeholder="serviceType ==='就医陪诊' ? '请输入接送地址' :  serviceType ==='上门陪护' ? '请输入陪护地址' : '请输入接收地址'"
            :class="{'custom-label':userStore.userInfo.ageGroup === 1}"
            :rules="[{ required: true, message: '请输入地址' },
            {
              pattern: /^[\u4e00-\u9fa5A-Za-z0-9\s\-/]{5,100}$/, // 正则表达式校验地址格式
              message: '地址必须为5-100个字符，且只能包含中文、英文、数字、空格和常见符号',
            },]"
          />
          <van-field
            v-if="serviceType ==='上门陪护'"
            v-model="escortType"
            label="陪护类型"
            placeholder="请选择陪护类型"
            readonly
            is-link
            @click="showEscortTypePicker = true"
            :rules="[{ required: true, message: '请选择陪护类型' }]"
            :class="{'custom-label':userStore.userInfo.ageGroup === 1}"
          />
        </van-cell-group>
      </div>

      <!-- 就诊时间 -->
      <div class="form-block" v-if="serviceType ==='就医陪诊' || serviceType ==='诊前约号'">
        <div class="block-title">就诊时间</div>
        <van-cell-group inset>
          <van-field
            v-model="visitDate"
            label="就诊日期"
            placeholder="请选择就诊日期"
            readonly
            is-link
            @click="showDatePicker = true"
            :class="{'custom-label':userStore.userInfo.ageGroup === 1}"
            :rules="[{ required: true, message: '请选择就诊日期' }]"
          />
          <van-field
            v-model="visitTime"
            label="就诊时间"
            placeholder="请选择就诊时间"
            readonly
            is-link
            @click="showTimePicker = true"
            :class="{'custom-label':userStore.userInfo.ageGroup === 1}"
            :rules="[{ required: true, message: '请选择就诊时间' }]"
          />
        </van-cell-group>
      </div>
        <!-- 执行服务人员 -->
      <div class="form-block">
        <div class="block-title">服务专员信息</div>
        <van-cell-group inset>
          <van-field
            v-model="formData.serviceStaffName"
            label="服务专员"
            placeholder="请选择服务专员"
            readonly
            is-link
            @click="showServicePicker = true"
            :rules="[{ required: true, message: '请选择服务专员信息' }]"
            :class="{'custom-label':userStore.userInfo.ageGroup === 1}"
          />
          <van-field
            v-model="servicePersonneAge"
            label="专员年龄"
            placeholder="服务专员年龄"
            readonly
            is-link
            :class="{'custom-label':userStore.userInfo.ageGroup === 1}"
          />
          <van-field
            v-model="formData.serviceStaffPhone"
            label="联系电话"
            placeholder="服务专员联系电话"
            readonly
            is-link
            :class="{'custom-label':userStore.userInfo.ageGroup === 1}"
          />
        </van-cell-group>
      </div>

      <!-- 备注信息 -->
      <div class="form-block">
        <div class="block-title">备注信息</div>
        <van-cell-group inset>
          <van-field
            v-model="formData.remark"
            label="备注"
            type="textarea"
            placeholder="请输入备注信息（选填）"
            rows="2"
            autosize
            :class="{'custom-label':userStore.userInfo.ageGroup === 1}"
          />
        </van-cell-group>
      </div>

      <!-- 服务协议 -->
      <div class="agreement">
        <van-checkbox v-model="agreement" shape="square">
          我已阅读并同意
          <span class="link" @click="showUserAgreement">《用户协议》</span>
          和
          <span class="link" @click="showServiceAgreement">《服务协议》</span>
        </van-checkbox>
      </div>

      <!-- 提交按钮 -->
      <div class="submit-btn">
        <div class="price-info">
          <span>实付金额：</span>
          <span class="price">¥{{ servicePrice }}</span>
        </div>
        <van-button type="primary" block native-type="submit">
          确认下单（支付¥{{ servicePrice }}）
        </van-button>
      </div>
    </van-form>

    <!-- 医院选择器 -->
    <van-popup v-model:show="showHospitalPicker" position="bottom">
      <van-picker
        :columns="hospitalColumns"
        @confirm="onHospitalConfirm"
        @cancel="showHospitalPicker = false"
        show-toolbar
        title="选择医院"
      />
    </van-popup>

    <!-- 服务专员选择器 -->
    <van-popup v-model:show="showServicePicker" position="bottom">
      <van-picker
        :columns="servicePersonnelColumnsNew"
        @confirm="onServicePersonnelConfirm"
        @cancel="showServicePicker = false"
        show-toolbar
        title="选择执行服务的人员"
      />
    </van-popup>

    <!-- 服务对象选择器 -->
    <van-popup v-model:show="showPatientPicker" position="bottom">
      <van-picker
        :columns="patientColumns"
        @confirm="onPatientConfirm"
        @cancel="showPatientPicker = false"
        show-toolbar
        title="选择服务对象"
      />
    </van-popup>
    <!-- 上门陪护类型选择器 -->
    <van-popup v-model:show="showEscortTypePicker" position="bottom">
      <van-picker
        :columns="escortTypeColumns"
        @confirm="onEscortTypeConfirm"
        @cancel="showEscortTypePicker = false"
        show-toolbar
        title="选择陪护类型"
      />
    </van-popup>

    <!-- 日期选择器 -->
    <van-popup v-model:show="showDatePicker" position="bottom">
      <van-date-picker
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="onDateConfirm"
        @cancel="showDatePicker = false"
        title="选择就诊日期"
      />
    </van-popup>

    <!-- 时间选择器 -->
    <van-popup v-model:show="showTimePicker" position="bottom">
      <van-time-picker
        @confirm="onTimeConfirm"
        @cancel="showTimePicker = false"
        show-toolbar
        title="选择就诊时间"
      />
    </van-popup>
    <!-- 支付密码弹框 -->
    <van-popup v-model:show="showPayPassowrd" position="bottom" :close-on-click-overlay="false">
      <van-icon style="position: relative;top: 10px;right: -5px;font-size: 30px" name="arrow-left" @click="router.push('/order')"/><span style="    font-size: 20px;position: relative;top: 6px;right: -5px;" @click="router.push('/order')">取消</span>
      <div class="pay-title">请输入支付密码</div>
      <div class="pay-title-tip">向{{formData.hospitalName}}转账</div>
      <h1 style="text-align:center">¥{{ servicePrice }}</h1>
      <!-- 密码输入框 -->
      <van-password-input
      :value="payPassword"
      :focused="showKeyboard"
      style="margin-bottom: 500px;"
      @focus="showKeyboard = true"
      />
     <!-- 数字键盘 -->
     <van-number-keyboard
      v-model="payPassword"
      :show="showKeyboard"
      @blur="showKeyboard = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, onMounted, watch} from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showDialog } from 'vant'
import { stafflApi, hospitalApi, orderApi ,serviceObjectApi } from '@/api'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore()

const router = useRouter()
const route = useRoute()

// 当前进度步骤
const currentStep = ref(0)

// 服务类型信息映射
const serviceTypeMap = {
  '就医陪诊': {
    name: '就医陪诊',
    desc: '专业陪诊，全程无忧',
    img: new URL('../../assets/images/jiuyipeizhen.png', import.meta.url).href,
    code: 1
  },
  '诊前约号': {
    name: '诊前约号',
    desc: '提前预约，省心省力',
    img: new URL('../../assets/images/zhenqianyuehao.png', import.meta.url).href,
    code: 2
  },
  '送取就医结果': {
    name: '送取就医结果',
    desc: '安全快捷，专人送取',
    img: new URL('../../assets/images/songqujieguo.png', import.meta.url).href,
    code: 3
  },
  '代跑取药': {
    name: '代跑取药',
    desc: '专业人员代您取药，安全便捷',
    img: new URL('../../assets/images/daipao.png', import.meta.url).href,
    code: 4
  },
  '上门陪护': {
    name: '上门陪护',
    desc: '专业护理，贴心服务',
    img: new URL('../../assets/images/shangmenpeihu.png', import.meta.url).href,
    code: 5
  }
}

// 修改服务类型信息的响应式变量
const serviceType = ref('')
const serviceDescription = ref('')
const serviceImg = ref('')
const serviceCode = ref(null)
const servicePrice = ref(null)

// 表单数据
const formData = ref({
  hospitalId:null,
  hospitalName: '',
  serviceObject: '',
  serviceObjectPhone: '',
  serviceStaffName:'',
  serviceStaffPhone:'',
  remark: '',
  staffId:null
})
const address = ref('')//接送地址或接收地址或陪护地址
const visitDate = ref('')//就诊日期
const visitTime = ref('')//就诊时间
const departmentName = ref('')//就诊科室
const doctorName = ref('')//就诊科室
const idNumber = ref('')//身份证号
const medicalCardNumber = ref('')//就诊卡号
const result = ref('')//诊断结果
const deliveryCode = ref('')//取药码
const medicalNumber = ref('')//医保卡号
const escortType = ref('')//陪护类型
const agreement = ref(false)

// 医院选择器
const showHospitalPicker = ref(false)
const hospitalColumns = ref([])  // 这里应该从接口获取医院列表
const departmentColumns = ref([])  // 这里应该从接口获取科室列表

// 就诊人选择器
const showPatientPicker = ref(false)
const patientColumns = ref([])  // 这里应该从接口获取就诊人列表

// 日期选择器
const showDatePicker = ref(false)
const minDate = new Date()
const maxDate = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000)

// 时间选择器
const showTimePicker = ref(false)

// 返回上一页
const onClickLeft = () => {
  router.back()
}

// 医院选择器确认事件处理
const onHospitalConfirm = ({ selectedOptions }) => {
  formData.value.hospitalName = selectedOptions[0].text
  formData.value.hospitalId = selectedOptions[0].value
  getPrice()
}


const getServiceObjectList = async (userId) =>{
  try{
    let params = {
    userId:userId,
  }
  const res = await serviceObjectApi.getServiceObjectList(params)
  if(res.code === 200){
  patientColumns.value = res.data.list.map(item =>({
    text:item.objectName,
    value:item.id,
    address:item.address,
    age:item.age,
    phone:item.phone
  }))
    // 设置默认服务对象
    let defaultPatientData = res.data.list.find(item => item.defaultPatient === 1)
  if (defaultPatientData) {
    formData.value.serviceObject = defaultPatientData.objectName
    formData.value.serviceObjectPhone = defaultPatientData.phone
    if (serviceType.value === '就医陪诊' || serviceType.value === '送取就医结果' || serviceType.value === '代跑取药' || serviceType.value === '上门陪护') {
      address.value = defaultPatientData.address
    }
  }
  }else{
    showToast('获取服务对象列表失败')
  }
  }catch(error){
    console.log(error)
    showToast('获取服务对象列表失败')
  }
}

// 服务对象选择器确认事件处理
const onPatientConfirm = ({ selectedOptions }) => {
  formData.value.serviceObject = selectedOptions[0].text
  formData.value.serviceObjectPhone = selectedOptions[0].phone
  if(serviceType.value ==='就医陪诊' || serviceType.value ==='送取就医结果' || serviceType.value ==='代跑取药' || serviceType.value ==='上门陪护'){
    address.value = selectedOptions[0].address
    console.log('address',address.value)
  }
  showPatientPicker.value = false
}

// 日期选择确认
const onDateConfirm = (value) => {
  visitDate.value = formatDate(value)
  showDatePicker.value = false
}

// 时间选择确认
const onTimeConfirm = (value) => {
  visitTime.value = formatTime(value)
  showTimePicker.value = false
}

// 格式化日期
const formatDate = (date) => {
  const year = String(date.selectedValues[0])
  const month = String(date.selectedValues[1])
  const day = String(date.selectedValues[2])
  return `${year}-${month}-${day}`
}
// 格式化时间
const formatTime = (time) => {
  const hour = String(time.selectedValues[0])
  const minutes = String(time.selectedValues[1])
  return `${hour}:${minutes}`
}

// 显示用户协议
const showUserAgreement = () => {
  showDialog({
    title: '用户协议',
    message: '1、本协议是用户（以下简称"您"）与就医陪诊平台（以下简称"本平台"）之间关于使用本平台服务的法律协议\n2、请您在使用本平台服务前仔细阅读本协议。当您注册、登录或使用本平台服务时，即表示您已充分理解并同意接受本协议的全部内容\n3、本平台有权根据需要修改本协议，修改后的协议将在本平台公布后生效。如您继续使用本平台服务，视为您接受修改后的协议',
    confirmButtonText: '我知道了'
  })
}

// 显示服务协议
const showServiceAgreement = () => {
  showDialog({
    title: '服务协议',
    message: '1、本协议是用户（以下简称"您"）与就医陪诊平台（以下简称"本平台"）之间关于使用本平台服务的法律协议\n2、请您在使用本平台服务前仔细阅读本协议。当您注册、登录或使用本平台服务时，即表示您已充分理解并同意接受本协议的全部内容\n3、本平台有权根据需要修改本协议，修改后的协议将在本平台公布后生效。如您继续使用本平台服务，视为您接受修改后的协议',
    confirmButtonText: '我知道了'
  })
}

// 提交表单
const onSubmit = async () => {
  if (!agreement.value) {
    showToast('请先同意用户协议和服务协议')
    return
  }
  // // 表单验证
  // if (!departmentName.value) {
  //   showToast('请选择就诊科室')
  //   return
  // }
  // if (!formData.value.serviceObject) {
  //   showToast('请选择就诊人')
  //   return
  // }
  // if (!visitDate.value) {
  //   showToast('请选择就诊日期')
  //   return
  // }
  // if (!visitTime.value) {
  //   showToast('请选择就诊时间')
  //   return
  // }


  // TODO: 提交订单
  try{
  formData.value.serviceName = serviceType.value
  formData.value.serviceCode = serviceCode.value
  formData.value.userId = JSON.parse(localStorage.getItem('userInfo') ).id
  formData.value.username = JSON.parse(localStorage.getItem('userInfo') ).nickname
  formData.value.orderAmount = Number(servicePrice.value)
  if(serviceType.value === '就医陪诊' && address.value && visitDate.value && visitTime.value){
    formData.value.businessContent = 'address:' + address.value + ',' + 'visitDate:' + visitDate.value + ',' + 'visitTime:' + visitTime.value + ',' + 'servicePersonneAge:' + servicePersonneAge.value
  }else if(serviceType.value === '诊前约号' && visitDate.value && visitTime.value && departmentName.value && doctorName.value){
    formData.value.businessContent = 'departmentName:' + departmentName.value + ',' + 'doctorName:' + doctorName.value + ',' + 'visitDate:' + visitDate.value + ',' + 'visitTime:' + visitTime.value  + ',' + 'servicePersonneAge:' + servicePersonneAge.value
  }else if(serviceType.value === '送取就医结果' && idNumber.value && medicalCardNumber.value && address.value){
    formData.value.businessContent = 'idNumber:' + idNumber.value + ',' + 'medicalCardNumber:' + medicalCardNumber.value + ',' + 'address:' + address.value  + ',' + 'servicePersonneAge:' + servicePersonneAge.value
  }else if (serviceType.value === '代跑取药' && result.value && deliveryCode.value && idNumber.value && medicalNumber.value && address.value){
    formData.value.businessContent = 'result:' + result.value + ',' + 'deliveryCode:' + deliveryCode.value + ',' + 'idNumber:' + idNumber.value + ',' + 'medicalNumber:' + medicalNumber.value + ',' + 'address:' + address.value  + ',' + 'servicePersonneAge:' + servicePersonneAge.value
  }else if(serviceType.value === '上门陪护' && escortType.value && address.value){
    formData.value.businessContent = 'escortType:' + escortType.value + ',' +'address:' + address.value  + ',' + 'servicePersonneAge:' + servicePersonneAge.value
  }
  formData.value = filterEmptyFields(formData.value)
  let  havePayPassword = JSON.parse(localStorage.getItem('userInfo'))
  if(havePayPassword.hasPayPassword === 1){
    showToast('请先设置支付密码')
    return
  }
  console.log('提交订单:', formData.value)
  const res = await orderApi.addOrders(formData.value)
  if(res.code === 200){
    orderId.value = res.data.id
    showPayPassowrd.value = true
    showToast('下单成功')
  }else{
    showToast('下单失败')
  }
  } catch(error) {
    console.error('下单失败：', error)
    showToast('下单失败')
  }
  // router.push('/order')
}
//过滤字段值为空的订单参数
const filterEmptyFields = (data) => {
  const filteredData = {};

  for (const key in data) {
    if (data[key] !== null && data[key] !== undefined && data[key] !== '' && data[key] !== "") {
      filteredData[key] = data[key];
    }
  }

  return filteredData;
};
const orderId = ref(null)//订单号
const payOrder = async () => {
  try {
    let params = {
      orderId: Number(orderId.value),
      payPassword: payPassword.value
    }
    const res = await orderApi.payOrder(params) 
    if (res.code === 200) {
      orderId.value = null
      payPassword.value = ''
      showPayPassowrd.value = false
      formData.value = {}
      router.push('/order')
      showToast('支付成功')
    } else {
      // orderId.value = null
      payPassword.value = ''
      // showPayPassowrd.value = false
      showToast(`支付失败${res.message}`)
    }
  } catch (error) {
    // orderId.value = null
    payPassword.value = ''
    // showPayPassowrd.value = false
    console.log('支付失败', error)
    showToast(`支付失败${error}`)
  }
}


const showPayPassowrd = ref(false)
const payPassword = ref('')
const showKeyboard = ref(true)
watch(payPassword, (newValue) => {
  if (newValue && newValue.length === 6) {
    payOrder()
  }
});


const getPrice = async () =>{
  let params = {
    hospitalId:formData.value.hospitalId
  }
  const res = await hospitalApi.getHospitalServices(params)
  if(res.code === 200){
     let serviceMessage = res.data.filter(item => item.serviceName === serviceType.value && item.status === 1)
     if(serviceMessage[0]?.price !== null&&serviceMessage.length>0){
     servicePrice.value = serviceMessage[0]?.price
     showHospitalPicker.value = false
    }else{
      formData.value.hospitalName = null
      formData.value.hospitalId = null
      showToast(`该医院的${serviceType.value}服务已停用，请选择其他医院`)
    }
  }
}
const isDisabled = ref(true)

// 修改初始化数据方法
const initializeData = async () => {
  const data = route.query
  console.log('路由参数:', data)
  
  if (data.type && serviceTypeMap[data.type]) {
    const serviceInfo = serviceTypeMap[data.type]
    serviceType.value = serviceInfo.name
    serviceDescription.value = serviceInfo.desc
    serviceImg.value = serviceInfo.img
    serviceCode.value = serviceInfo.code
    servicePrice.value = data.price
    formData.value.hospitalName = data.hospitalName
    formData.value.hospitalId = Number(data.hospitalId)
    if(data.hospitalName && data.hospitalId){
      isDisabled.value = false
    }
    if(!servicePrice.value){
      showToast('请先选择医院信息，再提供服务价格')
    }
  } else {
    // 默认值或错误处理
    showToast('服务类型不存在')
    router.back()
  }
}

//获取执行服务人员信息
const showServicePicker = ref(false)
const servicePersonneAge = ref('')
const servicePersonnelColumns = ref([])
const getServicePersonnelList = async () => {
  let params = {
      page:1,
      size:10000
    }
    const res = await stafflApi.getStaffList(params)
    if(res.code === 200){
      servicePersonnelColumns.value = res.data.list
      .filter(personnel =>personnel.status === 1 && personnel.serviceType.includes(serviceType.value))
      .map(item =>({
        text:item.staffName,
        value:item.id,
        staffPhone:item.staffPhone,
        age:item.age,
        staffId:item.id,
        hospitalId:item.hospitalId
      }))
    }else {
      showToast('获取服务专员列表失败')
    }
}

const servicePersonnelColumnsNew = ref([])
watch(
  () => formData.value.hospitalId, // 监听的具体字段
  async (newValue, oldValue) => {
    await getServicePersonnelList()
        servicePersonnelColumnsNew.value = servicePersonnelColumns.value.filter(item => {
      return item.hospitalId === Number(newValue)
    })
  }
);
// 执行人员选择器确认事件处理
const onServicePersonnelConfirm = ({ selectedOptions }) => {
  console.log('selectedOptions',selectedOptions[0])
  formData.value.serviceStaffName = selectedOptions[0].text
  formData.value.serviceStaffPhone = selectedOptions[0].staffPhone
  formData.value.staffId = selectedOptions[0].staffId
  servicePersonneAge.value = selectedOptions[0].age
  showServicePicker.value = false
}

//获取上门陪护类型信息
const showEscortTypePicker = ref(false)
const escortTypeColumns = ref([
  {
    text:' 基础生活护理',
    value:' 基础生活护理'
  },
  {
    text:' 医疗护理',
    value:' 医疗护理'
  },
  {
    text:' 心理支持',
    value:' 心理支持'
  },
  {
    text:' 特殊护理',
    value:' 特殊护理'
  },
  {
    text:' 家庭支持',
    value:' 家庭支持'
  },
  {
    text:' 上门打针',
    value:' 上门打针'
  },
  {
    text:' 健康教育与指导',
    value:' 健康教育与指导'
  },
])
const onEscortTypeConfirm = (item) => {
  console.log('item',item.selectedValues[0])
  if(item.selectedValues[0]){
    showToast({
      message: '请在备注里填写服务要求或联系执行服务人员进行沟通',
      duration: 5000
    })
  }
  escortType.value = item.selectedValues[0]
  showEscortTypePicker.value = false
}

// 获取医院列表
const getHospitalList = async () => {
  try {
    let params = {
      page:1,
      size:10000
    }
    const res = await hospitalApi.getHospitalList(params)
    if (res.code === 200) {
      hospitalColumns.value = res.data.records
      .filter(hospitalItem => hospitalItem.services.includes(serviceTypeMap[serviceType.value].code))
      .map(item => ({
        text: item.name,
        value: item.id
      }))
    }
  } catch (error) {
    console.error('获取医院列表失败：', error)
    showToast('获取医院列表失败')
  }
}

onMounted(async () => {
  await initializeData()
  await getHospitalList()
  await getServicePersonnelList()
  let userId =JSON.parse(localStorage.getItem('userInfo')).id
  await getServiceObjectList(userId)
  // 其他初始化...
})
</script>

<style lang="scss" scoped>
.service {
  padding-bottom: 100px;

  .progress-bar {
    padding: 20px 16px;
    background: #fff;
    margin-bottom: 12px;
  }

  .service-type {
    display: flex;
    align-items: center;
    padding: 16px;
    background: #fff;
    margin-bottom: 12px;

    .service-icon {
      width: 48px;
      height: 48px;
      border-radius: 8px;
      overflow: hidden;
      margin-right: 12px;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }

    .service-info {
      flex: 1;

      .service-name {
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 4px;
      }

      .service-desc {
        font-size: 12px;
        color: var(--text-color-secondary);
      }
    }
  }

  .form-block {
    margin-bottom: 12px;

    .block-title {
      padding: 0 16px;
      margin-bottom: 8px;
      font-size: 14px;
      font-weight: 500;
      color: var(--text-color);
    }
  }

  .agreement {
    padding: 16px;
    font-size: 12px;

    .link {
      color: var(--primary-color);
    }
  }

  .submit-btn {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 8px 16px;
    background: #fff;
    border-top: 1px solid var(--border-color);
    display: flex;
    align-items: center;
    justify-content: space-between;

    .price-info {
      font-size: 14px;

      .price {
        font-size: 20px;
        font-weight: 500;
        color: #ee0a24;
      }
    }

    .van-button {
      flex: 1;
      margin-left: 16px;
    }
  }
  .pay-title{
    margin-left: 115px;
    margin-top: 20px;
    margin-bottom: 20px;
    font-size: 20px;
    font-weight: 800
  }
  .pay-title-tip{
    text-align: center;
    margin-top: 20px;
    margin-bottom: 20px;
    font-size: 20px;
    font-weight: 800
  }
  .custom-label ::v-deep .van-field__label {
  font-size: 20px !important;
}
}
</style> 